import {EChartsParams} from "@/assets/utils/eChartsParams";

/**
 * 初始化图表
 * @param id div的id
 * @param option
 */
export const initECharts = (id:string, option:{})=>{
  let echarts = require('echarts');
  let myChart = echarts.init(document.getElementById(id));
  myChart.setOption(option);
  return myChart;
}

/**
 * 制作data
 * @param list  数据列表
 * @param xKey  横坐标数据的key
 * @param yKey  纵坐标数据的key
 * @param xRender   y的value变化方法
 * @param yRender   y的value变化方法
 */
export const makeData = (list:any[], xKey:string, yKey:string, xRender?:(xValue:any)=>any, yRender?:(yValue:any)=>any) =>{
  let data: { x: any, y: any }[] = []
  list.forEach((n) => {
    data.push({x: xRender !== undefined ? xRender(n[xKey]) : n[xKey], y: yRender !== undefined ? yRender(n[yKey]) : n[yKey]})
  })
  return data;
}

/**
 * 获取Option
 */
export const getOption = (params:EChartsParams) =>{
  // 组装legend.data和xAxis.data,series
  let legendData:string[] = []
  let xAxisData:string[] = []
  let series:any[] = []
  params.dataArray?.forEach((n)=>{
    // 记录legend
    legendData.push(n.legend)
    // 遍历n.data，记录xAxisData和seriesData
    let seriesData:any[] = []
    n.data?.forEach((m)=>{
      // 记录xAxisData
      if(xAxisData.indexOf(m.x) == -1){
        xAxisData.push(m.x)
      }
      seriesData.push(m.y)
    })
    // 录入series
    series.push({
      name: n.legend,
      type: params.type,
      data: seriesData,
      // 折线图：显示为平滑曲线
      smooth: params.smooth || false,
      // 柱状图：柱体最大宽度
      barMaxWidth:50
    })
  })

  return {
    title: {
      text: params.title
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: legendData,
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    xAxis: {
      type: 'category',
      // 是否从零点开始（false为从零点开始，一般用于折线图）
      boundaryGap: params.type === "line" ? false : true,
      data: xAxisData
    },
    yAxis: {
      type: 'value'
    },
    series: series
  }
}
